﻿using System;
using System.Web;
using OpenPhotoAlbum.BusinessLogics;
using OpenPhotoAlbum.Controls;

namespace OpenPhotoAlbum
{
	public class AlbumWebService : System.Web.Services.WebService
	{
		public AlbumWebService()
		{
		}

		protected Guid UserId
		{
			get
			{
				if (!UserManager.Instance.IsUserLoggedIn)
					return Guid.Empty;

				string userName = HttpContext.Current.User.Identity.Name;

				Guid cacheKey = GuidUtility.Combine(userName, AlbumPage.SaltUserId);

				if (CacheManager.Instance.ContainsKey(cacheKey))
					return CacheManager.Instance.ReadCache<Guid>(cacheKey);

				Guid userId = UserManager.Instance.GetUser(userName).UserId;
				CacheManager.Instance.WriteCache<Guid>(cacheKey, userId);

				return userId;
			}
		}

		protected bool AssertAlbumOwner(Guid albumId)
		{
			Guid userId = OwnerCache.Instance.GetAlbumOwner(albumId).UserId;

			if (userId == null
				|| userId.Equals(Guid.Empty)
				|| !userId.Equals(this.UserId))
			{
				throw new OwnerValidationFailureException();
			}
			return true;
		}

		protected bool AssertPhotoOwner(Guid photoId)
		{
			Guid userId = OwnerCache.Instance.GetPhotoOwner(photoId).UserId;

			if (userId == null
				|| userId.Equals(Guid.Empty)
				|| !userId.Equals(this.UserId))
			{
				throw new OwnerValidationFailureException();
			}
			return true;
		}

		protected void AssertCommentOwner(Guid commentId)
		{
			if (HttpContext.Current.User.IsInRole(BusinessLogics.RoleNames.Administrator)) { return; }
			string userName = CommentManager.Instance.GetCommentOwner(commentId);
			if (!userName.Equals(HttpContext.Current.User.Identity.Name, StringComparison.InvariantCultureIgnoreCase))
			{ throw new OwnerValidationFailureException(); }
		}
	}

	public class OwnerValidationFailureException : Exception { }
}
